package com.typing.battle.view;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.typing.battle.R;
import com.typing.battle.activity.TypingBattleChatRoomActivity;
import com.typing.battle.async.ImageAsync;
import com.typing.battle.database.FriendManager;
import com.typing.battle.listener.OnDataSyncCompleteListener;
import com.typing.battle.receiver.ServerPollingReceiver;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.value.ServerComunicationDTO;

public class FriendListViewForDefault extends ListView implements OnItemClickListener,OnDataSyncCompleteListener{

	private Context mContext;
	private Activity mActivity;
	//private ArrayList<FriendDTO> list;
	private JSONArray list;
	private FriendListAdapter adapter;
	private LinearLayout layout;
	public TextView vDescript,vName,vBlock;
	private ImageView vThumb;
	private LayoutInflater inflate;
	private PreferenceMgr mgr;
	private int rowCount = 15;
	private int currentIndex = 0;
	private int totalCount;
	private String searchText;
	public FriendListViewForDefault(Context context) {
		super(context);
		mContext = context;
		mActivity = (Activity)context;
		mgr = PreferenceMgr.getInstance(context);
		inflate = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//		getData();
		adapter =new FriendListAdapter();
		setAdapter(adapter);
		setOnItemClickListener(this);
		
	}
	public void searchFriend(String str){
		searchText = str;
		if(adapter != null){
			currentIndex = 0;
			list = new JSONArray();
			getData();
			adapter.notifyDataSetChanged();
		}
	}
	public void RefreshData(){
		
		if(adapter != null){
			currentIndex = 0;
			list = new JSONArray();
			getData();
			adapter.notifyDataSetChanged();
		}
	}
	public void getNextList(){
		getData();
		adapter.notifyDataSetChanged();
	}
	private void getData(){
			/*dbMgr = new FriendManager(mContext);
			m_db = dbMgr.open();
	    	// rawQuery 함수를 이용한 데이터 질의
	    	return dbMgr.getFriends("SELECT * FROM "+FriendManager.DATABASE_TABLE + " ORDER BY "+FriendManager.KEY_NAME+" ASC", null);
			*/
		ServerComunicationDTO dto = new ServerComunicationDTO();
		dto.setActionType(ServerComunicationUtil.TYPE_FRIEND_SELECT);
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
		dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
		if(searchText != null && !searchText.trim().equals("")){
			dto.setFriendName(searchText);
		}
		dto.setStartIndex(currentIndex);
		dto.setEndIndex(currentIndex + rowCount);
		try{
			ServerComunicationUtil.serverAction(dto,mContext,FriendListViewForDefault.this);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public class FriendListAdapter extends BaseAdapter{
		
		

		@Override
		public int getCount() {
			return list !=null ? list.length() : 0;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
//			Log.d("", "getView===>>"+position);
			if(convertView ==null){
				layout  = (LinearLayout)inflate.inflate(R.layout.friend_list_row, null);
			}else{
				layout =(LinearLayout)convertView;	
			}
			
			vThumb = (ImageView)layout.findViewById(R.id.thumb_friend_name);
			vDescript = (TextView)layout.findViewById(R.id.label_friend_descript);
			vName = (TextView)layout.findViewById(R.id.label_friend_name);
			vBlock = (TextView)layout.findViewById(R.id.label_block_yn);
			try{
				JSONObject obj1 = new JSONObject(list.get(position).toString());
				String email =obj1.get("friendEmail").toString();
				ImageAsync sync= new ImageAsync(mActivity, "http://www.typoong.com/upload/"+email+"_image.jpg", vThumb);
//				vThumb.setImageBitmap(getProfileImage(email));
				vDescript.setText(obj1.get("friendDescript").toString());
				vName.setText(obj1.get("friendName").toString());
				vBlock.setText("Y".equals(obj1.get("connectYn").toString()) ? "On":"Off");
				
				
				if(!"Y".equals(obj1.get("connectYn").toString())){
					vName.setTextColor(mContext.getResources().getColor(R.color.silver));
					vBlock.setTextColor(mContext.getResources().getColor(R.color.silver));
				}else{
					vName.setTextColor(mContext.getResources().getColor(R.color.black));
					vBlock.setTextColor(mContext.getResources().getColor(R.color.red));
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			return layout;
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		//Intent intent = new Intent(mContext, TypingBattleChatRoomActivity.class);
		//intent.putExtra("friend_data", list.get(position));	
		//mActivity.setResult(1,intent);
		//mActivity.finish();
		// TODO Auto-generated method stub
		JSONObject obj = null;
		String email = null;
		boolean connectYn = false;
		try {
			obj = new JSONObject(list.get(position).toString());
			email = obj.get("friendEmail").toString();
			if("Y".equals(obj.get("connectYn").toString())){
				  connectYn = true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		final String friendEmail = email;
		DialogInterface.OnClickListener goChatListener = new DialogInterface.OnClickListener() 
	    { 
		  
	      @Override 
	      public void onClick(DialogInterface dialog, int which) 
	      { 
	    	  
				
	    	    ServerComunicationDTO dto = new ServerComunicationDTO();
				dto.setActionType(ServerComunicationUtil.TYPE_BATTLE_INVITE);
				dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
				dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
				dto.setSendType(ServerPollingReceiver.TYPE_INVITE);
				dto.setChatRoomName(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, "") + "&" + friendEmail);
		    	dto.setChatRoomOwner(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
		    	dto.setChatRoomType("9");
		    	dto.setMaxPeopleCount("2");
				//dto.setFriendEmail(friendEmail);
				dto.setReceiveEmail(friendEmail);
				try {
					ServerComunicationUtil.serverAction(dto, mContext,FriendListViewForDefault.this);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
	      } 
	    }; 
	     
	    DialogInterface.OnClickListener blockFriendListner = new DialogInterface.OnClickListener() 
	    { 
	      @Override 
	      public void onClick(DialogInterface dialog, int which) 
	      { 
	    	  	ServerComunicationDTO dto = new ServerComunicationDTO();
				dto.setActionType(ServerComunicationUtil.TYPE_FRIEND_UPDATE);
				dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
				dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
				//dto.setSendType(ServerPollingReceiver.);
				dto.setFriendEmail(friendEmail);
				dto.setBlockYn("Y");
				String result = null;
				try {
					ServerComunicationUtil.serverAction(dto, mContext,FriendListViewForDefault.this);
				} catch (Exception e) {
					e.printStackTrace();
				}
	      } 
	    }; 
	     
	    DialogInterface.OnClickListener deleteFriendListner = new DialogInterface.OnClickListener() 
	    { 
	      @Override 
	      public void onClick(DialogInterface dialog, int which) 
	      { 
	    	  	ServerComunicationDTO dto = new ServerComunicationDTO();
				dto.setActionType(ServerComunicationUtil.TYPE_FRIEND_DELETE);
				dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
				dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
				//dto.setSendType(ServerPollingReceiver.TYPE_INVITE);
				dto.setFriendEmail(friendEmail);
				String result = null;
				try {
					ServerComunicationUtil.serverAction(dto, mContext,FriendListViewForDefault.this);
				} catch (Exception e) {
					e.printStackTrace();
				}
	      } 
	    }; 
	    if(connectYn){
		    new AlertDialog.Builder(mContext) 
		      .setTitle("메뉴") 
		      .setPositiveButton("1:1 대화하기", goChatListener) 
		      .setNeutralButton("친구차단", blockFriendListner) 
		      .setNegativeButton("친구삭제", deleteFriendListner) 
		      .show(); 
	    }else{
	    	new AlertDialog.Builder(mContext) 
		      .setTitle("메뉴") 
		      .setNeutralButton("친구차단", blockFriendListner) 
		      .setNegativeButton("친구삭제", deleteFriendListner) 
		      .show(); 
	    }
	}
	public int getTotalCount(){
		return this.totalCount;
	}
	public int getCurrentIndex(){
		return this.currentIndex;
	}
	
	@Override
	public void onSyncComplete(int resultCode, ServerComunicationDTO dto, Object resultObj) {
		String result;
		if(resultCode == OnDataSyncCompleteListener.RESULT_SYNC_FAIL){
			if(resultObj!=null)
				ServerComunicationUtil.showNotify((String)resultObj, mContext);
		}else{
			if(dto.getActionType() == ServerComunicationUtil.TYPE_FRIEND_DELETE){
				
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_FRIEND_UPDATE){
				
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_BATTLE_INVITE){
				try {
					result = (String)resultObj;
					Intent intent = new Intent(mContext,TypingBattleChatRoomActivity.class);
	        		dto = new ServerComunicationDTO();
	    			dto.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_JOIN);
	    			dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
	    			dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
	    			dto.setChatRoomId(result);
	    			intent.putExtra("CHAT_ROOM_ID", result);
	    			try{
	    				ServerComunicationUtil.serverAction(dto,mContext);
	    			}catch(Exception e){
	    				
	    			}
	    			mContext.startActivity(intent);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_FRIEND_SELECT){
				try{
					
					JSONObject resultObject = new JSONObject((String)resultObj);
					JSONArray friendArray = new JSONArray(resultObject.get("friendList").toString());
					JSONArray inviteArray = new JSONArray(resultObject.get("inviteList").toString());
					//list 초기화.
					if(friendArray!=null && friendArray.length()>0)	list = new JSONArray();
					for(int i = 0 ; i < friendArray.length(); i++){
						list.put(friendArray.get(i)); 
					}
					if(list==null || list.length()<1){
						((View)this.getParent()).setVisibility(GONE);
					}else{
						((View)this.getParent()).setVisibility(VISIBLE);
					}
					totalCount = resultObject.getInt("totalCount");
					currentIndex = currentIndex + rowCount;
					adapter.notifyDataSetChanged();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
//		super.onSyncComplete(resultCode, dto, resultObj);
	}

	@Override
	public void onSyncComplete(int resultCode) {
		// TODO Auto-generated method stub
		
	}
}

